package bbs.controller;

import bbs.entity.config.WebConfig;
import bbs.entity.dto.TongYiDto;
import bbs.entity.enums.TongyiTypeEnum;
import bbs.service.TongYiService;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;


@RestController
@RequestMapping("/ai")
@CrossOrigin
public class TongYiController {

    private static final Logger logger = LoggerFactory.getLogger(TongYiController.class);

    @Autowired
    private WebConfig webConfig;

    @Autowired
    private TongYiService tongYiSimpleService;

    @RequestMapping(value = "/messageStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> messageStream(
            @RequestParam(value = "message") String message
    ) throws NoApiKeyException, InputRequiredException {
            try {
                Constants.apiKey = webConfig.getApiKey();
                Generation gen = new Generation();
                Message userMsg = Message.builder().role(Role.USER.getValue()).content(message).build();
                Flux<ServerSentEvent<String>> serverSentEventFlux = tongYiSimpleService.streamCallWithMessage(gen, userMsg);
                return serverSentEventFlux;
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                logger.error("发生异常: {}", e.getMessage());
            }

        return Flux.empty();
    }

    @RequestMapping(value = "/readImg")
    public String readImg(@RequestBody TongYiDto dto) throws NoApiKeyException, UploadFileException {
        String message = dto.getMessage();
        if (message == null || message.equals("")) {
            message = "请描述图片内容";
        }
        MultiModalConversationResult res = tongYiSimpleService.readImage(message, dto.getImg());
        return res.getOutput().getChoices().get(0).getMessage().getContent().get(0).toString();
    }

    @RequestMapping(value = "/summarize", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public String summarize(@RequestBody TongYiDto dto) throws NoApiKeyException, UploadFileException {
        String message = dto.getMessage();
        MultiModalConversationResult res = null;
        if (dto.getType().equals(TongyiTypeEnum.SUMMARIZE.getDesc())) {
            res = tongYiSimpleService.notStream("总结一下这段文章的重点：" + "“" + message + "”");
        }else {
            res = tongYiSimpleService.notStream("帮我重新写一遍这段话，要突出重点并且尽量让他看起更“专业”：" + "“" + message + "”");
        }
        return  res.getOutput().getChoices().get(0).getMessage().getContent().get(0).toString();
    }
}
